package com.zy.explore.license.infrastructure.util.mock;

import com.github.javafaker.Faker;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;

/**
 * description  Faker 方法名解析
 * 通过字符串解析后，调用 Faker 方法，如
 * name.name => faker.name().name();
 *
 * @author 🇨🇳中国印🇨🇳
 * @date 2022年04月17日 01:33:12
 */
public class FakerNameResolver extends Faker {

    private final static Faker cnFaker = Faker.instance(Locale.CHINA);
    private final static Faker enFaker = Faker.instance(Locale.ENGLISH);

    public static String resolve(String key, String lang) {
        Faker faker = "en".equals(lang) ? enFaker : cnFaker;
        return resolve(key, faker);
    }

    private static String resolve(String key, Faker faker) {
        String dot = ".";
        if (!key.contains(dot)) {
            throw new ResolveNotFoundException("不支持解析 [" + key + "]");
        }

        String[] split = key.split("[.]");
        String fakerMethod = split[0];
        String categoryMethod = split[1];

        Object fakerCategory = call(faker, fakerMethod);

        return call(fakerCategory, categoryMethod).toString();
    }

    private static Object call(Object target, String methodName) {
        Method method = ReflectionUtils.findMethod(target.getClass(), methodName);

        if (method == null) {
            throw new ResolveNotFoundException("方法 [" + methodName + "] 找不到");
        }

        try {
            return method.invoke(target);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new ResolveNotFoundException("方法 [" + methodName + "] 调用失败");
        }
    }
}
